<?php

namespace Beerus\Modules\SamsungActivity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\SamsungActivity\SamsungJoinUserListModel;
use Biz\model\SamsungActivity\SamsungVoteRecordModel;
use Biz\pockets\excel\DownExcel;
use Biz\service\SamsungActivity\SamsungJoinUserListService;
use Doraemon\model\Member as mMember;
use Doraemon\service\User;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Layout\Content;
use Exception;
use Illuminate\Http\Request;

class IndexController extends Controller
{
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        if (is_null($request->input('addtime'))) {
            $startTime = date("Y-m-d", strtotime("-1 day", time()));
            $request->merge([
                'addtime' => [
                    'start' => $startTime,
                    'end' => date('Y-m-d H:i:s', strtotime($startTime) + 86399),
                ],
                'per_page' => self::PAGE_SIZE,
            ]);
        }
        $params = $request->all();

        if (isset($params['addtime']['start']) && isset($params['addtime']['end'])) {
            $where['addtime[>=]'] = $params['addtime']['start'];
            $where['addtime[<]'] = $params['addtime']['end'];
        }

        $where['status'] = SamsungJoinUserListModel::STATUS_NORMAL;
        $where['ORDER'] = ['addtime' => "DESC"];

        $total = SamsungJoinUserListModel::count($where);

        if ($where) {
            $search_params = http_build_query($where);
        } else {
            $search_params = [];
        }

        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        $list = SamsungJoinUserListModel::selectByWhere($where);
        $data = [];
        if ($list) {
            $uidArr = array_unique(array_filter(array_column($list, 'uid')));
            $userList = User::getBatchBasicUserInfo($uidArr);
            $userList = array_column($userList, null, 'uid');
            foreach ($list as $row) {
                $userInfo = [];
                $uid = $row['uid'];
                if ($uid > 0) {
                    $userInfo = (isset($userList[$uid])) ? $userList[$uid] : [];
                }
                $dataRow = [
                    'id' => $row['id'],
                    'uid' => $uid ?? '',
                    'nick' => $userInfo ? $userInfo['nick'] : $row['nick'],
                    'name' => $row['name'] ?? '',
                    'phone' => $row['phone'] ?? '',
                    'profession_name' => $userInfo ? mMember::$typeDesc[$userInfo['type']] : $row['profession_name'],
                    'agency' => $row['agency'] ?? '',
                    'idea' => $row['idea'] ?? '',
                    'desc' => $row['desc'] ?? '',
                    'tv_type_name' => $row['tv_type_name'] ?? '',
                    'artist_name' => $row['artist_name'] ?? '',
                    'addtime' => $row['addtime'] ?? '',
                ];
                $data[] = $dataRow;
            }
        }

        $gridModel = new pGridDataModel($data, $total);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search_params) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();

            $grid->filter(function (Filter $filter) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->between('addtime', '添加时间')->datetime();
                //条件展开
                $filter->expand();
            });
            // 添加导出按钮
            $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                $url = url('/admin/samsungActivity/join/exportList?'.$search_params);
                $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出三星活动报名名单</span></a>
                    </div>';
                $tool->append($button);
            });
            $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                $url = url('/admin/samsungActivity/join/voteRecord?'.$search_params);
                $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出投票数据</span></a>
                    </div>';
                $tool->append($button);
            });
            $grid->column('id', '主键id')->width(100);
            $grid->column('uid', 'uid')->width(100);
            $grid->column('name', '姓名')->width(100);
            $grid->column('nick', '昵称')->width(100);
            $grid->column('phone', '手机号')->width(100);
            $grid->column('profession_name', '职业')->width(100);
            $grid->column('agency', '机构')->width(100);
            $grid->column('tv_type_name', '电视型号')->width(100);
            $grid->column('artist_name', '所选艺术家')->width(100);
            $grid->column('addtime', '添加时间')->width(100);

        });

        return $content
            ->header('三星活动名单')
            ->body($listGrid);

    }

    /**
     * 导出测评名单
     * @param \Illuminate\Http\Request $request
     * @return void
     */
    public function exportList(Request $request)
    {
        try {
            $params = $request->all();
            $where = [];
            if (isset($params['addtime']) && !empty($params['addtime'])) {
                $where['addtime[>=]'] = $params['addtime']['>='];
                $where['addtime[<]'] = $params['addtime']['<'];
            }
            if (isset($params['status']) && !empty($params['status'])) {
                $where['status'] = $params['status'];
            }
            if (isset($params['ORDER']) && !empty($params['ORDER'])) {
                $where['ORDER'] = $params['ORDER'];
            }
            $where['LIMIT'] = 100;
            $pageTitle = '三星活动数据导出'.date('Y-m-d H-i-s');

            $list = SamsungJoinUserListModel::selectByWhere($where);
            SamsungJoinUserListService::exportList($list, SamsungJoinUserListService::SAVE_TYPE_OUTPUT, $pageTitle);
        } catch (Exception $exception) {
            Log::error('三星活动导出异常', $exception);
        }
    }

    /**
     * 导出投票名单
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse|void
     */
    public function voteRecord(Request $request)
    {
        $lists = [];
        $list = SamsungJoinUserListModel::selectByWhere(['status' => SamsungJoinUserListModel::STATUS_SHOW], ['id']);
        if ($list) {
            $ids = array_column($list, 'id');
            //批量查询投票数
            $countMap = SamsungVoteRecordModel::getCountMaps(
                [
                    'obj_id' => $ids,
                    'status' => SamsungVoteRecordModel::STATUS_NORMAL,
                    "GROUP" => "obj_id",
                ]
            );
            $countMap = array_column($countMap, 'cnt', 'obj_id');


            foreach ($ids as $id) {
                $uidList = [];
                $nickList = [];
                $uidArr = SamsungVoteRecordModel::query("select uid from samsung_vote_record  where length(uid) < 32 and status =1 and obj_id={$id}")->fetchAll();
                $uidIds = array_unique(array_filter(array_column($uidArr, 'uid')));
                if (!empty($uidIds)) {
                    $userList = User::getBasicUserInfosByCache($uidIds);
                    if (!empty($userList)) {
                        foreach ($userList as $item) {
                            $uidList[] = $item['uid'];
                            $nickList[] = $item['nick'];
                        }
                    }
                }
                $lists[] = [
                    'id' => $id,
                    'voteNum' => $countMap[$id] ?? 0,
                    'uids' => implode(',', $uidList),
                    'nicks' => implode(',', $nickList),
                ];
            }
        }
        $header = [
            '作品ID',
            '投票数',
            'uid',
            '昵称',
        ];
        $excel_obj = new DownExcel();
        $excel_obj->setFileName('三星活动-投票记录-'.date('Y-m-d-H-i-s'));
        $excel_obj->setSheetTitle('三星活动-投票记录');

        // 设置列宽
        $widths = [
            'A' => 15,
            'B' => 15,
            'C' => 100,
            'D' => 100,
        ];

        $excel_obj->setWidth($widths);
        $excel_obj->setDefaultStyleAlignment();
        $excel_obj->setTextFormat('A');
        $excel_obj->setTextFormat('C');
        $excel_obj->setTextFormat('D');

        $excel_obj->create($lists, $header);
    }
}